const db = wx.cloud.database();
const voteimgList = db.collection('voteImgList');
const voteList = db.collection('votes');
let _ = db.command;
const $ = db.command.aggregate;

Page({
  data: {
    imgList: [],
    vote: false,
    swiperCurrent: 0,
  },
  onClickLeft() {
    wx.navigateBack({
      delta: 1,
    })
  },
  onLoad(option) {
    //图片获取
    voteimgList.get().then(res => {
      let list = res.data
      //console.log(res)
      this.setData({
        imgList: list
      })
      /**跳转到该图片适合swiper */
      if (typeof (option) == 'string') {
        this.setData({
          swiperCurrent: list.length - 1
        })
      }
    });

  },
  swiper({ detail }) {
    this.setData({
      swiperCurrent: detail.current
    })
  },
  async voteBtn({ currentTarget }) {
    var res = "", whereRes = "";
    var voteImgres = "";
    var groupRes = "";
    whereRes = await voteList.where({
      filedId: currentTarget.dataset.id
    }).get();

    groupRes = await wx.cloud.callFunction({
      name: "login"
    });
    let openid = groupRes.result.openid


    if (whereRes.data.length > 0) {
      //不为空时
      whereRes.data.forEach(element => {
        if (element.filedId == currentTarget.dataset.id && element._openid == openid) {

          if (element.voteCount < 3) {
            voteimgList.doc(currentTarget.dataset.id)
              .update({
                data: {
                  voteCount: _.inc(1),
                  isStyle: true
                }
              });
            voteList.where({
              filedId: currentTarget.dataset.id,
              _openid: openid
            }).update({
              data: {
                voteCount: _.inc(1),
              }
            }).then(res => {
              wx.showToast({
                title: '还有' + (2 - element.voteCount) + '次投票机会',
                icon: 'success'
              })
            });

            this.onLoad()
          } else {
            wx.showToast({
              title: '超过投票次数',
              icon: 'error'
            })
          }
        }
      });
    } else {
      //为空时
      res = await voteList.add({
        data: {
          voteCount: 1,
          filedId: currentTarget.dataset.id
        }
      });
      voteImgres = await voteimgList.doc(currentTarget.dataset.id).update({
        data: {
          voteCount: _.inc(1),
          isStyle: true
        }
      });
    }

    try {
      if ((res.errMsg.indexOf('ok') > -1) && (voteImgres.errMsg.indexOf('ok') > -1)) {
        wx.showToast({
          title: '投票成功',
        })
      };
    } catch (e) {

    }

    this.onLoad()
  },

  /**
  * 异步上传
  */
  async long() {
    let res = await wx.chooseImage({
      count: 1,
    })
    // console.log(res)
    let filename = res.tempFilePaths[0];
    let purfileName = filename.split('/').slice(-1)[0];
    res = await wx.cloud.uploadFile({
      cloudPath: 'voteImg/' + purfileName,
      filePath: filename
    })
    // console.log(res)
    let filedid = res.fileID;
    res = await voteimgList.add({
      data: {
        voteCount: 0,
        voteImg: filedid
      }
    });
    if (res.errMsg.indexOf('ok') > -1) {
      wx.showToast({
        title: '上传图片成功',
      });
      this.onLoad(filedid);
    }
  },
})